<?php
/**
 * Created by PhpStorm
 * @author: yiyu
 * @time: 2020/3/3 21:11
 * @desc: 跑马灯
 * @fileName: MarqueeService.php
 */

namespace app\api\service;

use app\base\service\BaseService;
use app\base\model\goods\{GoodsBaseInfo,
    GoodsGroupJoinInfo,
    GoodsPlatformInfo,
    GoodsGroupInfo,
    GoodsStatisticsInfo};
use app\base\model\user\{User, UserFriend, UserAccount, UserAccountLog, UserStatisticsInfo};
use app\base\model\system\SystemConfig;
use app\base\model\address\UserPostInfo;
use app\base\model\order\Order;
use app\base\service\Pay\OrderService;
use app\api\service\ShareService;
use app\core\exception\{BusinessException, ErrorCode};
use app\core\cache\{RedisCache, RedisKeys};
use app\core\log\Log4dd;
use think\Db;

class MarqueeService extends BaseService
{

    public $user_infos = [];
    public $user_nicks = [];


    public $goods_infos = [];

    public $friend_ids = [];

    const REPLACE_SYMBOL = '${xinyuanzhi}';

    public $replace_symbol = '';

    public function __construct()
    {
        $this->replace_symbol = config('heart_icon');
    }

    public static function getHomeMarquee($user_id, $limit = 10)
    {

        $replace_symbol = config('heart_icon');
        $list = [];
        $friend_joins = $stranger_joins = [];
        //获取我的好友
        $friend_ids = UserFriend::getMyFriend($user_id);

        if ($friend_ids) {
            //获取好友的支持记录
            $friend_joins = GoodsGroupJoinInfo::alias('j')
                ->join('xy_goods.xy_goods_group_info g', 'j.group_id=g.group_id')
                ->field('j.user_id,g.user_id as i_user_id,j.get_gold_num')
                ->whereIn('j.user_id', $friend_ids)
                //->where('j.create_time', '>', date('Y-m-d H:i:s', strtotime('-7 days')))
                ->order('j.join_id', 'desc')
                ->limit($limit)
                ->select();


            $limit = $limit - count($friend_joins);
        }

        if ($limit > 0) {
            //获取非好友支持记录
            $stranger_joins = GoodsGroupJoinInfo::alias('j')
                ->join('xy_goods.xy_goods_group_info g', 'j.group_id=g.group_id')
                ->field('j.user_id,g.user_id as i_user_id,j.get_gold_num')
                ->whereNotIn('j.user_id', $friend_ids)
                ->order('j.join_id', 'desc')
                ->limit($limit)
                ->select();
        }

        $joins = array_merge($friend_joins, $stranger_joins);

        if ($joins) {
            foreach ($joins as $join) {
                $nick_name = self::instance()->getUserNickName($join['user_id']);//支持者
                $i_nick_name = self::instance()->getUserNickName($join['i_user_id']);//发起者
                $list[] = $nick_name . '支持了' . $i_nick_name . '的心愿，得到' . $replace_symbol . (float)$join['get_gold_num'] . '！';
            }
        }

        return $list;

    }


    public static function getGoodsDetailMarquee($user_id, $goods_id, $limit = 10)
    {
        UserFriend::getMyFriend($user_id);
        $num = 0;
        $list = [];
        for ($offset = 0; $offset < 10; $offset++) {
            if ($num >= $limit) {
                break;
            }

            for ($type = 1; $type < 7; $type++) {
                if ($num >= $limit) {
                    break;
                }
                $copy_writing = self::instance()->getCopyWriting($user_id, $goods_id, $type, $offset);
                if ($copy_writing) {
                    $list[] = $copy_writing;
                    $num++;
                }
            }
        }

        return $list;
    }

    public static function getWishDetailMarquee($user_id, $goods_id, $limit = 5)
    {
        UserFriend::getMyFriend($user_id);
        $num = 0;
        $list = [];
        for ($type = 7; $type < 12; $type++) {
            if ($num >= $limit) {
                break;
            }
            $copy_writing = self::instance()->getCopyWriting($user_id, $goods_id, $type, 1);
            if ($copy_writing) {
                $list[] = $copy_writing;
                $num++;
            }
        }

        return $list;
    }

    public function getCopyWriting($user_id, $goods_id, $type, $offset)
    {
        Log4dd::info('getCopyWriting', func_get_args());
        $result = [];
         switch ($type){
             case 1://XXX刚刚发起了该好物心愿，心愿即将达成！——3小时内发起当前好物心愿
                 $query = GoodsGroupInfo::where('goods_id', $goods_id)
                     ->where('create_time', '>', date('Y-m-d H:i:s', strtotime('-3 hours')))
                     ->order('group_id', 'desc');

                 if ($this->friend_ids) {
                     $query->whereIn('user_id', $this->friend_ids);
                 }
                 $info = $query->limit($offset,1)->field('user_id,group_id')->select();

                 if ($info && $i_user_id = $info[0]['user_id']) {
                     $user_info = self::instance()->getUserInfo($i_user_id);
                     $result = [
                         'avatar_url' => $user_info['avatar_url'],
                         'group_id' => $info[0]['group_id'],
                         'copy_writing' => $user_info['nick_name'] . '刚刚发起了该好物心愿，心愿即将达成！'
                     ];
                 }
                 break;
             case 2://XXX发起了XXXXXX 心愿——心愿发起记录
                 $query = GoodsGroupInfo::order('group_id', 'desc');

                 if ($this->friend_ids) {
                     $query->whereIn('user_id', $this->friend_ids);
                 }
                 $info = $query->field('user_id,goods_id,group_id')->limit($offset,1)->select();

                 if ($info) {
                     $group_info = array_shift($info);
                     $user_info = self::instance()->getUserInfo($group_info['user_id']);
                     $result = [
                         'avatar_url' => $user_info['avatar_url'],
                         'group_id' => $group_info['group_id'],
                         'copy_writing' => $user_info['nick_name'] . '发起了' . self::instance()->getGoodsName($group_info['goods_id']) . '心愿'
                     ];
                 }
                 break;
             case 3://XXX将他的心愿分享给了好友——随机选一个机器人做一条假数据
                 $info = GoodsGroupInfo::alias('g')
                     ->join('xy_user.xy_user u', 'u.user_id=g.user_id')
                     ->where('u.account_type', User::ACCOUNT_TYPE_ROBOT)
                     ->order('g.group_id', 'desc')
                     ->limit($offset,30)
                     ->field('u.nick_name,u.small_avatar_url,g.group_id')
                     ->select();

                 if ($info) {
                     shuffle($info);
                     $user_info = array_shift($info);
                     $result = [
                         'avatar_url' => $user_info['small_avatar_url'],
                         'group_id' => $user_info['group_id'],
                         'copy_writing' => $user_info['nick_name'] . '将他的心愿分享给了好友'
                     ];
                 }
                 break;
             case 4://XXX的心愿在1小时内达成，太快了！——在1小时内达标的心愿
                 $info = GoodsGroupInfo::where('group_state', GoodsGroupInfo::GROUP_SUCCESS_STATE)
                     ->where('success_time', '<>', '')
                     ->order('group_id', 'desc')
                     ->limit($offset,1)
                     ->field('user_id,group_id,UNIX_TIMESTAMP(success_time) as s_time,UNIX_TIMESTAMP(create_time) as c_time')
                     ->having('s_time - c_time <= 3600')
                     ->select();
                 if ($info && $i_user_id = $info[0]['user_id']) {
                     $user_info = self::instance()->getUserInfo($i_user_id);
                     $result = [
                         'avatar_url' => $user_info['avatar_url'],
                         'group_id' => $info[0]['group_id'],
                         'copy_writing' => $user_info['nick_name'] . '的心愿在1小时内达成，太快了！'
                     ];
                 }
                 break;
             case 5://XXX的心愿得到X名圈友支持，太受欢迎！——得到支持次数大于3次的心愿
                 $info = GoodsGroupInfo::where('join_people', '>=', 3)
                     ->order('group_id', 'desc')
                     ->field('user_id,join_people,group_id')
                     ->limit($offset,1)
                     ->select();
                 if ($info) {
                     $group_info = array_shift($info);
                     $user_info = self::instance()->getUserInfo($group_info['user_id']);
                     $result = [
                         'avatar_url' => $user_info['avatar_url'],
                         'group_id' => $group_info['group_id'],
                         'copy_writing' => $user_info['nick_name'] . '的心愿得到' . $group_info['join_people'] . '名圈友支持，太受欢迎！'
                     ];
                 }
                 break;
             case 6://XXX的心愿得到X人支持，成功拿下好物！——达标记录
                 $info = GoodsGroupInfo::where('group_state', GoodsGroupInfo::GROUP_SUCCESS_STATE)
                     ->order('group_id', 'desc')
                     ->limit($offset,1)
                     ->field('user_id,join_people,group_id')
                     ->select();
                 if ($info) {
                     $group_info = array_shift($info);
                     $user_info = self::instance()->getUserInfo($group_info['user_id']);
                     $result = [
                         'avatar_url' => $user_info['avatar_url'],
                         'group_id' => $group_info['group_id'],
                         'copy_writing' => $user_info['nick_name'] . '的心愿得到' . $group_info['join_people'] . '人支持，成功拿下好物！'
                     ];
                 }
                 break;
             case 7://XXX支持他人心愿后成功发起新的心愿！——有过支持记录的人发起的心愿
                 $query = GoodsGroupInfo::alias('g')
                     ->join('xy_goods.xy_goods_group_join_info j', 'j.user_id=g.user_id')
                     ->order('g.group_id', 'desc');

                 if ($this->friend_ids) {
                     $query->whereIn('g.user_id', $this->friend_ids);
                 }
                 $info = $query->limit($offset,1)->field('g.user_id,g.group_id')->select();
                 if ($info && $i_user_id = $info[0]['user_id']) {
                     $user_info = self::instance()->getUserInfo($i_user_id);
                     $result = [
                         'avatar_url' => $user_info['avatar_url'],
                         'group_id' => $info[0]['group_id'],
                         'copy_writing' => $user_info['nick_name'] . '支持他人心愿后成功发起新的心愿！'
                     ];
                 }
                 break;
             case 8://XXX刚刚支持他人心愿获得了N心愿值！——3小时内的支持记录
                 $query = GoodsGroupJoinInfo::where('create_time', '>', date('Y-m-d H:i:s', strtotime('-3 hours')))
                     ->order('join_id', 'desc');

                 if ($this->friend_ids) {
                     $query->whereIn('user_id', $this->friend_ids);
                 }
                 $info = $query->limit($offset, 1)->field('user_id,get_gold_num,group_id')->select();
                 if ($info) {
                     $group_info = array_shift($info);
                     $user_info = self::instance()->getUserInfo($group_info['user_id']);
                     $result = [
                         'avatar_url' => $user_info['avatar_url'],
                         'group_id' => $group_info['group_id'],
                         'copy_writing' => $user_info['nick_name'] . '刚刚支持他人心愿获得了' . $this->replace_symbol . (float)$group_info['get_gold_num'] . '！'
                     ];
                 }
                 break;
             case 9://XXX用心愿值发起了数据线收纳磁吸器心愿——心愿发起记录
                 $query = GoodsGroupInfo::order('group_id', 'desc');

                 if ($this->friend_ids) {
                     $query->whereIn('user_id', $this->friend_ids);
                 }
                 $info = $query->field('user_id,goods_id,group_id')->limit($offset,1)->select();
                 if ($info) {
                     $group_info = array_shift($info);
                     $user_info = self::instance()->getUserInfo($group_info['user_id']);
                     $result = [
                         'avatar_url' => $user_info['avatar_url'],
                         'group_id' => $group_info['group_id'],
                         'copy_writing' => $user_info['nick_name'] . '用心愿值发起了' . self::instance()->getGoodsName($group_info['goods_id']) . '心愿'
                     ];
                 }
                 break;
             case 10://XXX一次性获得N心愿值！——支持记录
                 $info = GoodsGroupJoinInfo::order('join_id', 'desc')->limit($offset, 1)->field('user_id,get_gold_num,group_id')->select();
                 if ($info) {
                     $group_info = array_shift($info);
                     $user_info = self::instance()->getUserInfo($group_info['user_id']);
                     $result = [
                         'avatar_url' => $user_info['avatar_url'],
                         'group_id' => $group_info['group_id'],
                         'copy_writing' => $user_info['nick_name'] . '一次性获得' . $this->replace_symbol . (float)$group_info['get_gold_num'] . '！'
                     ];
                 }
                 break;
             case 11://XXX一次性获得N心愿值！——支持记录
                 $info = GoodsGroupJoinInfo::order('join_id', 'desc')->limit($offset + 1, 1)->field('user_id,get_gold_num,group_id')->select();
                 if ($info) {
                     $group_info = array_shift($info);
                     $user_info = self::instance()->getUserInfo($group_info['user_id']);
                     $result = [
                         'avatar_url' => $user_info['avatar_url'],
                         'group_id' => $group_info['group_id'],
                         'copy_writing' => $user_info['nick_name'] . '一次性获得' . $this->replace_symbol . (float)$group_info['get_gold_num'] . '！'
                     ];
                 }
                 break;

         }

         return $result;
    }

    public function getFriendIds($user_id)
    {
        $this->friend_ids = UserFriend::getMyFriend($user_id);
    }

    public function getUserInfo($user_id)
    {
        if (empty($user_id)) {
            return [
                'nick_name' => '好友',
                'avatar_url' => ''
            ];
        }

        if (!isset($this->user_infos[$user_id])) {
            $user_info = User::getUserInfoById($user_id, ['nick_name', 'small_avatar_url']);
            $this->user_infos[$user_id] = [
                'nick_name' => isset($user_info['nick_name']) && $user_info['nick_name'] ? $user_info['nick_name'] : '好友',
                'avatar_url' => isset($user_info['small_avatar_url']) && $user_info['small_avatar_url'] ? $user_info['small_avatar_url'] : '',
            ];
        }

        return $this->user_infos[$user_id];
    }

    public function getUserNickName($user_id)
    {
        if (empty($user_id)) {
            return '好友';
        }

        if (!isset($this->user_nicks[$user_id])) {
            $nick_name = User::getUserFieldById($user_id, 'nick_name');
            $this->user_nicks[$user_id] = empty($nick_name) ? '好友' : $nick_name;
        }

        return $this->user_nicks[$user_id];
    }
    
    public function getGoodsName($goods_id)
    {

        if (empty($goods_id)) {
            return '好物';
        }

        if (!isset($this->goods_infos[$goods_id])) {
            $goods_name = GoodsBaseInfo::getGoodsBaseInfoByField($goods_id, 'goods_name');
            $this->goods_infos[$goods_id] = empty($goods_name) ? '好物' : $goods_name;
        }

        return $this->goods_infos[$goods_id];
    }

}